package com.xc.demo.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.xc.demo.common.Constants;
import com.xc.demo.entity.Employee;
import com.xc.demo.exception.ServiceException;
import com.xc.demo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private EmployeeService employeeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader("token");

        if(!(handler instanceof HandlerMethod))
        {
            return true;
        }


//        执行认证
        if(StrUtil.isBlank(token)){
           throw new ServiceException(Constants.CODE_401,"无token,请重新登录哦!");
        }

//        获取token中的user_id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (JWTDecodeException j){
            throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录哦!");
        }

//        根据TOKEN中的userid查询数据库
        Employee employee =employeeService.getById(userId);
        if(employee == null){
            throw new ServiceException(Constants.CODE_401,"用户不存在,请重新登录哦!");
        }

//        验证token,用用户密码加签
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(employee.getPassword())).build();
        try{
            jwtVerifier.verify(token); //验证token
        }catch (JWTDecodeException j){
            throw new ServiceException(Constants.CODE_401,"token验证失败,请重新登录哦!");
        }




        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
